<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\Users;
use app\model\kefu\Seating;
use app\model\UsersRoles;

class LoginController extends Base
{
	//用户登录
	public function index()
	{
		$postField = 'username,password,key';
		$data = $this->request->only(explode(',', $postField), 'post', null);

		if (empty($data['username'])) {
			throw new ValidateException('请输入验证码');
		}

		if (empty($data['username'])) {
			throw new ValidateException('请输入密码');
		}

		$res = $this->checkLogin($data);

		if ($res) {
			$token = $this->setToken($res);
			return $this->json(['data' => $res, 'token' => $token]);
		}
	}

	//验证登录
	private function checkLogin($data)
	{
		$where['username'] = $data['username'];
		$field = 'id,title,username,password,salt,create_time,status,role_id';
		$info =	Users::field($field)->where($where)->find();

		if ($info) {
			$info = $info->toArray();
			$UsersRoles = UsersRoles::field('title as roles_title,status as roles_status')->find($info['role_id']);
			$info['roles_title'] = $UsersRoles['roles_title'];
			$info['roles_status'] = $UsersRoles['roles_status'];
			if ($info['password'] === pass_hash($data['password'], $info["salt"], $info["create_time"])) {
				unset($info['password']);
				unset($info["salt"]);
				$Seating = Seating::field('uid,chatid,title,touxiang')->where('uid', $info['id'])->find();
				if (!empty($Seating)) {
					$Seating = $Seating->toArray();
					$info['serverChatEn']['iskf'] = 1;
					$info['serverChatEn']['serverChatId'] = $Seating['chatid'];
					$info['serverChatEn']['serverChatName'] = $Seating['title'];
					$info['serverChatEn']['avatarUrl'] = $Seating['touxiang'];
				}
				if (!($info['status']) || !($info['roles_status'])) {
					throw new ValidateException("该账户被禁用");
				}
			} else {
				throw new ValidateException("用户名或者密码不正确");
			}
		}

		event('LoginLog', $data['username']);	//写入登录日志

		return $info;
	}
}
